﻿$(function() {
    if ($('#readonly').length > 0) {
        $('input,textarea').attr('disabled', true).addClass('disabled');
        $('select').attr('disabled', true).addClass('disabled');
    }
    if ($('#returntoopeneraftersave').length > 0 && $('#returntoopeneraftersave').val() == 'true')
        addPersonToOrder($('#id').val() + '1');
});

//-----------tabs------------
function setTab(id) {
    if (!id) return;
    $('#tab').val(id);
    switch (id) {
		case 'tasks':
			if ($('#tasks table').length == 0) 
				loadTasks(false);
			break;
		case 'orders':
			if ($('#orders table').length == 0) 
				loadOrders(false);
			break;			
		case 'companies':
			if ($('#companies table').length == 0) 
				loadCompanies(false);
			break;						
    }
	$('.tab').hide();
	$('#' + id).show();
    $('#tabs>ul>li>a').removeClass('selected');
    $('#tabs>ul>li>a#a' + id).addClass('selected');
    return false;
}

function loadTasks(reload) {
    if (reload || !$.trim($('#tasks').html()))
        $('#tasks').load(base + 'task.ivp/loadpersontasks/', { tb_personid: $('#id').val(), timestamp: new Date() }, function() { initTable(); setTab('tasks'); });
    else setTab('tasks');
        return false;
}

function loadOrders(reload) {
    if (reload || !$.trim($('#orders').html()))
        $('#orders').load(base + 'order.ivp/loadpersonorders/', { tb_personid: $('#id').val(), timestamp: new Date() }, function() { initTable(); setTab('orders'); });
    else setTab('orders');
    return false;
}

function loadCompanies(reload) {
    if (reload || !$.trim($('#companies').html()))
        $('#companies').load(base + 'company.ivp/loadpersoncompanies/', { personid: $('#id').val(), timestamp: new Date() }, function() { initTable(); setTab('companies'); });
    else setTab('companies');
    return false;
}

//----------company links--------------
function chooseCompanies() {
    openDialog('company.ivp/select');
    return false;
}

function addSelected(companyid) {
    $.post("companyperson.ivp/addcompanyperson/", { timestamp: new Date(), companyid: companyid, personid: $('#id').val()}, function() {loadCompanies(true);});
	return false;
}

function deleteCompanies() {
    var ids = new Array();
    $('#companies input[name=id]:checked').each(function(i, el) { ids.push(el.value); });
    if (ids.length == 0) { alert('Ни одна запись не выбрана!'); return false; }
    if (!confirm('Вы уверены, что ходите удалить выбранные записи?')) return false;
    $.post(base + 'companyperson.ivp/deletecompanyperson', { timestamp: new Date(), personid: $('#id').val(), ids: ids}, function() { loadCompanies(true);});
    return false;
}

//-----------------external calls-----------------
function addPerson(id) {
    if (id && id > 0) 
    {
        var fio = $('#lastname').val() + ' ' + $('#name').val() + ' ' + $('#patronymicname').val();
        if (self.callback == null) self.callback = opener._personSelected;
        self.callback(id, fio, 'true');
    }
    self.close();
    return false;
}

function addPersonToOrder(id) {
    if (id && id > 0) {
        var fio = $('#lastname').val() + ' ' + $('#name').val() + ' ' + $('#patronymicname').val();
        if (self.callback == null) self.callback = opener.userSelected;
        self.callback(id, fio, false);
    }
    self.close();
    return false;
}

//-----------------helpers-----------------
function removeFile(id, name) {
    if (!confirm('Вы уверены, что хотите удалить файл?')) return false;
    
    $.getJSON('person.ivp/removefile/' + id, { date: new Date().toString() }, function(result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
			$('#'+name+'holder').hide();
			$('#input'+name+'holder').show();
		}
        else
            alert(result.Description);
    });
    return false;
}

function switchTelephoneInput(id) {
    var obj = $('#phone' + id);
    if (obj.val().toString().length == obj.attr('maxlength'))
        $('#phone' + (id + 1)).focus();
    return false;
}

//------------------union-------------

function selectPerson() {
    var dlg = openDialog('person.ivp/select?reset=true');
    dlg.callback = function(id) { _personSelected(id, dlg.userNames['un' + id.toString()]); }
    return false;
}

function personSelected(e, d) {
    var id = d[1];
    var name = d[0];
    $(e.target).val('');
    _personSelected(id, name);
}

function _personSelected(id, name, hideselect) {
	loadUnionSource(id);
    return false;
}

function unionField(field) {
	var src = $('#source #'+field.toString());	
	var dest = $('#destination #'+field.toString());
	if (src.val().length > 0)
		dest.val(dest.val() + ' ' + src.val());
	return false;
}

function replaceField(field) {
	var src = $('#source #'+field.toString());	
	var dest = $('#destination #'+field.toString());
	if ($('#source #' + field.toString()).attr('type') == 'checkbox')
		dest.attr('checked',src.attr('checked'));
	else
		dest.val(src.val());
	return false;
}

function loadUnionSource(id) {
	$('#source').load(base + 'person.ivp/loadunionsource/'+id, { nolayout: true, timestamp: new Date()},
		function() {$('#source input, #source textarea').attr('disabled', true); $('#unionpersonid').val(id);});
	return false;
}